package com.info.zhiduoduo.core.configs.jwt;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.info.zhiduoduo.core.vo.auth.UserAuthVO;

import java.util.Date;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtUtil {

	private static final String USER_KEY = "USER";
	private static final String SECRET = "dTX8dQ3l";

	public static String getToken(UserAuthVO user, Date expireAt) {
		return JWT.create()
				.withClaim(USER_KEY, JSON.toJSONString(user))
				.withIssuedAt(new Date())
				.withExpiresAt(expireAt)
				.sign(Algorithm.HMAC256(SECRET));
	}

	public static UserAuthVO parseUser(DecodedJWT jwt) {
		try {
			return JSON.parseObject(jwt.getClaim(USER_KEY).asString(), UserAuthVO.class);
		} catch (Exception e) {
			log.error("解析JWT的UserVO报错。");
		}
		return null;
	}

	public static DecodedJWT check(String token) throws Exception {
		return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
	}
}
